﻿using System;
using System.Collections.Generic;
using System.Linq;
using DataBaseLayer.Abstractions.Interfaces.Services;
using DataBaseLayer.Dto;
using DataBaseLayer.Extensions;

namespace DataBaseLayer.Services
{
	public class ScheduleService : IScheduleService
	{
		#region Variables

		private readonly churchDataBase _dataBase;

		#endregion

		#region Constructors

		public ScheduleService(churchDataBase dataBase)
		{
			if (dataBase == null)
				throw new ArgumentNullException(string.Format("data base"));

			_dataBase = dataBase;
		}

		#endregion

		#region ISheduleService Members

		public DateTime GetScheduleStartDate()
		{
			var day = _dataBase.ScheduleDays.OrderBy(sd => sd.DayId).FirstOrDefault();
			return day != null ? day.Date : DateTime.Now;
		}

		public void UpdateScheduleDates(DateTime date)
		{
			var dayDate = date;
			foreach (var day in _dataBase.ScheduleDays.OrderBy(sd => sd.DayId).ToList())
			{
				if (day != null)
					day.Date = dayDate;
				dayDate = dayDate.AddDays(1);
			}
			_dataBase.SaveChanges();
		}

		public IEnumerable<ScheduleDayData> GetDays()
		{
			return _dataBase.ScheduleDays.OrderBy(sd => sd.DayId).ToList().ToDTOs();
		}

		public IEnumerable<ScheduleServiceData> GetDayServicesByDayId(int dayId)
		{
			return _dataBase.ScheduleServices.Where(ss => ss.DayId == dayId).OrderBy(ss => ss.Time).ToList().ToDTOs();
		}

		public void UpdateIsSpecialDayParameterByDayId(int dayId, bool value)
		{
			var day = _dataBase.ScheduleDays.SingleOrDefault(sd => sd.DayId == dayId);
			if (day != null)
			{
				day.IsSpecialDay = value;
				_dataBase.SaveChanges();
			}
		}

		public void DeleteScheduleServiceById(int id)
		{
			var item = _dataBase.ScheduleServices.SingleOrDefault(ss => ss.ServiceId == id);
			if (item != null)
			{
				_dataBase.ScheduleServices.Remove(item);
				_dataBase.SaveChanges();
			}
		}

		public void CreateScheduleService(ScheduleServiceData entity)
		{
			if (entity != null)
			{
				var newItem = new DataBaseLayer.ScheduleService
				{
					DayId = entity.DayId,
					Name = entity.Name,
					ScheduleDay = _dataBase.ScheduleDays.SingleOrDefault(sd => sd.DayId == entity.DayId),
					ServiceId = entity.ServiceId,
					Time = entity.Time
				};
				_dataBase.ScheduleServices.Add(newItem);
				_dataBase.SaveChanges();
			}
		}

		public void UpdateScheduleService(ScheduleServiceData entity)
		{
			if (entity != null)
			{
				var oldItem = _dataBase.ScheduleServices.SingleOrDefault(ss => ss.ServiceId == entity.ServiceId);
				if (oldItem != null)
				{
					oldItem.Name = entity.Name;
					oldItem.Time = entity.Time;
					_dataBase.SaveChanges();
				}
			}
		}

		#endregion
	}
}
